package com.huixiong.nio.channel.server.bioserer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * bio 实现 client server 通信
 *
 * @author timothy.yang cloudwise
 * @since 2022-05-08 20:57
 */
public class BioServer extends Thread {
    private ServerSocket serverSocket;

    public int getPort() {
        return serverSocket.getLocalPort();
    }

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(0);
            ExecutorService executor = Executors.newFixedThreadPool(3);
            while (true) {
                Socket socket = serverSocket.accept();
                RequestHandler requestHandler = new RequestHandler(socket);
                executor.execute(requestHandler);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class RequestHandler extends Thread {
        private Socket socket;

        RequestHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                for (int i = 0; i < 10; i++) {
                    PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
                    printWriter.println("fuck world!");
                    printWriter.flush();
                    Thread.sleep(1000);
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        BioServer bioServer = new BioServer();
        bioServer.start();
        try {
            Socket client = new Socket(InetAddress.getLocalHost(), bioServer.getPort());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            bufferedReader.lines().forEach(
                    System.out::println
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
